package com.yxn.cloud.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.cloud.common.to.SkuHasStockVo;
import com.cloud.common.to.mq.OrderVo;
import com.cloud.common.utils.R;
import com.cloud.common.vo.MemberRespVo;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.yxn.cloud.order.constant.OrderConstant;
import com.yxn.cloud.order.dao.OrderItemDao;
import com.yxn.cloud.order.entity.OrderItemEntity;
import com.yxn.cloud.order.entity.OrderReturnReasonEntity;
import com.yxn.cloud.order.enums.OrderStatusEnum;
import com.yxn.cloud.order.exception.NoStockException;
import com.yxn.cloud.order.feign.CartFeignService;
import com.yxn.cloud.order.feign.MemberFeignService;
import com.yxn.cloud.order.feign.ProductFeignService;
import com.yxn.cloud.order.feign.WareFeignService;
import com.yxn.cloud.order.interceptor.LoginUserInterceptor;
import com.yxn.cloud.order.service.OrderItemService;
import com.yxn.cloud.order.to.OrderCreateTo;
import com.yxn.cloud.order.vo.*;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yxn.common.utils.PageUtils;
import com.yxn.common.utils.Query;

import com.yxn.cloud.order.dao.OrderDao;
import com.yxn.cloud.order.entity.OrderEntity;
import com.yxn.cloud.order.service.OrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.annotation.Resource;


@RabbitListener(queues = "CloudMissing-queue")
@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    public static ThreadLocal<OrderSubmitVo> thread_local = new ThreadLocal<>();

    @Resource
    OrderItemService orderItemService;

    @Resource
    MemberFeignService memberFeignService;

    @Resource
    CartFeignService cartFeignService;

    @Resource
    WareFeignService wareFeignService;

    @Resource
    ThreadPoolExecutor threadPoolExecutor;

    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Resource
    RabbitTemplate rabbitTemplate;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    @Resource
    ProductFeignService productFeignService;

    @Override
    public OrderConfirmVo confirmOrder() {
        OrderConfirmVo confirmVo = new OrderConfirmVo();
        MemberRespVo memberRespVo = LoginUserInterceptor.threadLocal.get();
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        //1、异步远程查询所有的收货地址列表
        CompletableFuture<Void> memberAddressFuture = CompletableFuture.runAsync(() -> {
            //设置主线程请求属性
            RequestContextHolder.setRequestAttributes(requestAttributes, true);
            List<MemberAddressVo> memberAddressVos = memberFeignService.queryMemberAddr(memberRespVo.getId());
            if (memberAddressVos != null) {
                confirmVo.setMemberAddress(memberAddressVos);
            }
        }, threadPoolExecutor);

        //2、获取订单内的购物车产品信息
        CompletableFuture<Void> cartItemFuture = CompletableFuture.runAsync(() -> {
            //设置主线程请求属性
            RequestContextHolder.setRequestAttributes(requestAttributes, true);
            List<OrderItemVo> currentUserItems = cartFeignService.getCurrentUserItems();
            if (currentUserItems != null) {
                confirmVo.setOrderItems(currentUserItems);
            }
        }, threadPoolExecutor).thenRunAsync(() -> {
            RequestContextHolder.setRequestAttributes(requestAttributes, true);
            List<OrderItemVo> orderItems = confirmVo.getOrderItems();
            List<Long> skuIds = orderItems.stream().map(item -> item.getSkuId()).collect(Collectors.toList());
            List<SkuHasStockVo> skusHasStock = wareFeignService.getSkusHasStock(skuIds);
            if (skusHasStock != null) {
                Map<Long, Boolean> skuStockMap = skusHasStock.stream().
                        collect(Collectors.toMap(SkuHasStockVo::getSkuId, SkuHasStockVo::getHasStock));
                confirmVo.setItemStockMap(skuStockMap);
            }
        }, threadPoolExecutor);

        //3、优惠信息，当前是以积分为例
        confirmVo.setIntegration(memberRespVo.getIntegration());
        //4、其他数据自动计算
        try {
            CompletableFuture.allOf(memberAddressFuture, cartItemFuture).get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        //todo 5、防重令牌
        String token = UUID.randomUUID().toString().replace("-", "");
        // 返回给页面的VO
        confirmVo.setOrderToken(token);
        stringRedisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId()
                , token, 10, TimeUnit.MINUTES);
        return confirmVo;
    }

    //    @GlobalTransactional
    @Transactional
    @Override
    public OrderSubmitRespVo submitOrder(OrderSubmitVo vo) {
        /**定义比价的最大差*/
        double maxCount = 0.01;
        OrderSubmitRespVo respVo = new OrderSubmitRespVo();
        thread_local.set(vo);
        respVo.setCode(0);
        MemberRespVo memberRespVo = LoginUserInterceptor.threadLocal.get();
        /**1、验令牌：核心在于令牌的对比和删除必须是原子性的*/
        String tokenKeyInRedis = OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId();
        String orderTokenInPage = vo.getOrderToken();
        String script = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
        Long compareResult = stringRedisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList(tokenKeyInRedis), orderTokenInPage);
        if (compareResult == 1L) {
            //比对成功
            /**1、下单  创建订单，验令牌，验价格，锁库存....*/
            OrderCreateTo orderCreateTo = createOrder();
            /**2、验价*/
            BigDecimal payPriceInDb = orderCreateTo.getEntity().getPayAmount();
            BigDecimal payPriceInPage = vo.getPayPrice();
            if (Math.abs(payPriceInPage.subtract(payPriceInDb).doubleValue()) < maxCount) {
                //如果页面传过来的值和数据库计算之后的差值在0.01范围之内都是可以的
                /**3、所有通过之后，下面就是保存订单数据*/
                saveOrderData(orderCreateTo);
                /**4、 锁库存 库存锁定，如果出现异常就会滚数据*/
                /** 订单号、所有订单项 （skuId、skuName，num）*/
                WareSkuLockVo lockVo = new WareSkuLockVo();
                lockVo.setOrderSn(orderCreateTo.getEntity().getOrderSn());
                /**将订单映射为我们想要的数据*/
                List<OrderItemVo> orderItemList = orderCreateTo.getItems().stream().map(item -> {
                    OrderItemVo orderItemVo = new OrderItemVo();
                    orderItemVo.setCount(item.getSkuQuantity());
                    orderItemVo.setSkuId(item.getSkuId());
                    orderItemVo.setTitle(item.getSkuName());
                    return orderItemVo;
                }).collect(Collectors.toList());
                lockVo.setItems(orderItemList);

                /**远程锁库存 为了保证高并发，库存服务可以自己回滚 可以发消息给库存*/
                R r = wareFeignService.orderLockStock(lockVo);
                Integer code = (Integer) r.get("code");
                if (0 == code) {
//                    int i = 10/0;
                    /**如果返回为零，说明锁定成功*/
                    respVo.setOrderEntity(orderCreateTo.getEntity());
                    //订单创建成功，发送消息给mq
                    rabbitTemplate.convertAndSend("order-event-exchange",
                            "order.create.order", orderCreateTo.getEntity());
                    return respVo;
                } else {
                    /**如果返回为其他，说明没有成功*/
                    String msg = (String) r.get("msg");
                    throw new NoStockException(msg);
                }

            } else {
                //如果差价不在0.01范围，说明比对失败
                respVo.setCode(2);
                return respVo;
            }
        } else {
            //比对失败
            respVo.setCode(1);
            return respVo;
        }
    }

    @Override
    public OrderEntity getOrderByOrderSn(String orderSn) {
        return this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
    }

    @Override
    public void closeOrder(OrderEntity orderEntity) {
        //在关闭前需要检查下订单状态，只有是未付款的情况下
        OrderEntity order = this.getById(orderEntity.getId());
        //关单
        if (OrderStatusEnum.CREATE_NEW.getCode().equals(order.getStatus())) {
            OrderEntity updateEntity = new OrderEntity();
            updateEntity.setId(orderEntity.getId());
            updateEntity.setStatus(OrderStatusEnum.CANCELED.getCode());
            this.updateById(updateEntity);

            OrderVo orderVo = new OrderVo();
            BeanUtils.copyProperties(order, orderVo);
            //发给mq一个释放库存的消息
            try {
                // 保证消息一定会发送出去，每一个消息都可以做好日志记录（给数据库保存每一个消息的详情信息）
                // 可以定期扫描数据库，未成功的消息进行重发
                rabbitTemplate.convertAndSend("order-event-exchange", "order.release.other", orderVo);
            } catch (AmqpException e) {
                //将没发送成功的消息重新尝试发送
                e.printStackTrace();
            }
        }
    }

    @Override
    public PayVo getOrderPay(String orderSn) {
        PayVo payVo = new PayVo();
        OrderEntity orderEntity = this.getOrderByOrderSn(orderSn);
        //设置精确到2位数，并向上取整
        BigDecimal bigDecimal = orderEntity.getTotalAmount().setScale(2, BigDecimal.ROUND_UP);
        payVo.setTotal_amount(bigDecimal.toString());
        payVo.setOut_trade_no(orderSn);
        List<OrderItemEntity> orderItemList = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", orderSn));
        payVo.setSubject(orderItemList.get(0).getSkuName());
        payVo.setBody(orderItemList.get(0).getSkuAttrsVals());
        return payVo;
    }

    /**
     * 保存订单数据
     *
     * @param order
     */
    private void saveOrderData(OrderCreateTo order) {
        /**保存订单数据*/
        OrderEntity entity = order.getEntity();
        entity.setModifyTime(new Date());
        this.save(entity);

        /**保存订单项数据*/
        List<OrderItemEntity> items = order.getItems();
        orderItemService.saveBatch(items);
    }

    /**
     * 创建订单
     *
     * @return
     */
    private OrderCreateTo createOrder() {
        OrderCreateTo createTo = new OrderCreateTo();
        String orderSn = IdWorker.getTimeId();
        /**1、创建订单*/
        OrderEntity orderEntity = buildOrder(orderSn);

        /**2、获取所有的订单项*/
        List<OrderItemEntity> orderItems = buildOrderItems(orderSn);

        /**3、验价  计算价格*/
        computePrice(orderEntity, orderItems);

        createTo.setEntity(orderEntity);
        createTo.setItems(orderItems);
        return createTo;
    }

    /**
     * 计算订单的总费用
     *
     * @param orderEntity
     * @param orderItems
     */
    private void computePrice(OrderEntity orderEntity, List<OrderItemEntity> orderItems) {
        /**总的金额*/
        BigDecimal total = new BigDecimal("0.0");
        /**总的打折金额*/
        BigDecimal promotionAmount = new BigDecimal("0.0");
        /**总的优惠券金额*/
        BigDecimal couponAmount = new BigDecimal("0.0");
        /**总的积分抵扣金额*/
        BigDecimal integrationAmount = new BigDecimal("0.0");
        for (OrderItemEntity orderItem : orderItems) {
            total = total.add(orderItem.getRealAmount());
            promotionAmount = promotionAmount.add(orderItem.getPromotionAmount());
            couponAmount = couponAmount.add(orderItem.getCouponAmount());
            integrationAmount = integrationAmount.add(orderItem.getIntegrationAmount());
        }
        /**1、设置订单相关的内容*/
        /**设置总额*/
        orderEntity.setTotalAmount(total);
        /**应付总额 : 总额 + 运费*/
        orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()));
        /**设置总的打折金额*/
        orderEntity.setPromotionAmount(promotionAmount);
        /**设置总的优惠金额*/
        orderEntity.setCouponAmount(couponAmount);
        /**设置总的积分抵扣金额*/
        orderEntity.setIntegrationAmount(integrationAmount);

    }

    /**
     * 构建所有订单项
     *
     * @return
     */
    private List<OrderItemEntity> buildOrderItems(String orderSn) {
        /**最后确定每个购物项的价格*/
        List<OrderItemVo> currentUserItems = cartFeignService.getCurrentUserItems();
        if (currentUserItems != null && currentUserItems.size() > 0) {
            List<OrderItemEntity> orderItems = currentUserItems.stream().map(item -> {
                OrderItemEntity orderItem = buildOrderItem(item);
                orderItem.setOrderSn(orderSn);
                return orderItem;
            }).collect(Collectors.toList());
            return orderItems;
        }
        return null;
    }

    /**
     * 构建每一个订单项
     *
     * @param item
     * @return
     */
    private OrderItemEntity buildOrderItem(OrderItemVo item) {
        OrderItemEntity orderItemEntity = new OrderItemEntity();
        /**1、订单信息：订单号*/
        /**2、商品的spu信息*/
        Long skuId = item.getSkuId();
        R spuR = productFeignService.getSpuBySkuId(skuId);
        SpuInfoVo spuEntity = spuR.getData(new TypeReference<SpuInfoVo>() {
        });
        orderItemEntity.setSpuId(spuEntity.getId());
        orderItemEntity.setSpuName(spuEntity.getSpuName());
        orderItemEntity.setCategoryId(spuEntity.getCatalogId());
        orderItemEntity.setSpuBrand(spuEntity.getBrandId().toString());

        /**3、商品的sku信息*/
        orderItemEntity.setSkuId(item.getSkuId());
        orderItemEntity.setSkuName(item.getTitle());
        orderItemEntity.setSkuPic(item.getImage());
        orderItemEntity.setSkuPrice(item.getPrice());
        String skuAttr = StringUtils.collectionToDelimitedString(item.getSkuAttr(), ";");
        orderItemEntity.setSkuAttrsVals(skuAttr);
        orderItemEntity.setSkuQuantity(item.getCount());
        /**4、商品的优惠信息(不做)*/
        /**商品促销分解金额*/
        orderItemEntity.setPromotionAmount(new BigDecimal("0.0"));
        /**优惠券优惠分解金额*/
        orderItemEntity.setCouponAmount(new BigDecimal("0.0"));
        /**积分优惠分解金额*/
        orderItemEntity.setIntegrationAmount(new BigDecimal("0.0"));
        /**原有的金额*/
        BigDecimal origin = item.getPrice().multiply(new BigDecimal(item.getCount().toString()));
        /**应付金额*/
        BigDecimal realAmount = origin.subtract(orderItemEntity.getPromotionAmount())
                .subtract(orderItemEntity.getCouponAmount())
                .subtract(orderItemEntity.getIntegrationAmount());
        orderItemEntity.setRealAmount(realAmount);

        /**5、商品的积分信息*/
        //成长积分
        orderItemEntity.setGiftGrowth(item.getCount().intValue());
        //会员积分
        orderItemEntity.setGiftIntegration(item.getPrice().intValue());

        return orderItemEntity;
    }

    /**
     * 构建订单
     *
     * @param orderSn
     * @return
     */
    private OrderEntity buildOrder(String orderSn) {
        /**使用mp提供的一个生成订单id的类*/
        OrderEntity entity = new OrderEntity();
        OrderSubmitVo orderSubmitVo = thread_local.get();
        entity.setOrderSn(orderSn);
        /**设置会员id*/
        MemberRespVo memberRespVo = LoginUserInterceptor.threadLocal.get();
        entity.setMemberId(memberRespVo.getId());
        /**远程获取运费*/
        R fareR = wareFeignService.getFare(orderSubmitVo.getAddrId());
        BigDecimal fare = fareR.getData(new TypeReference<BigDecimal>() {
        });
        entity.setFreightAmount(fare);
        /**远程获取地址*/
        R addressR = memberFeignService.queryAddressById(orderSubmitVo.getAddrId());
        MemberAddressVo addressVo = addressR.getData(new TypeReference<MemberAddressVo>() {
        });
        /**设置地址*/
        entity.setReceiverCity(addressVo.getCity());
        entity.setReceiverDetailAddress(addressVo.getDetailAddress());
        entity.setReceiverName(addressVo.getName());
        entity.setReceiverPhone(addressVo.getPhone());
        entity.setReceiverPostCode(addressVo.getPostCode());
        entity.setReceiverProvince(addressVo.getProvince());
        entity.setReceiverRegion(addressVo.getRegion());
        /**设置订单状态*/
        entity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        /**设置自动确认时间*/
        entity.setAutoConfirmDay(7);
        /**设置订单的删除状态 0 表示不删除 1 表示删除*/
        entity.setDeleteStatus(0);

        return entity;
    }

    /**
     * 在开启手动确认之后，必须在chanel中执行basicAck方法
     * 用来告诉broker，我确认这条消息收到了。
     *
     * @param entity
     * @param channel
     * @param message
     */
    @RabbitHandler
    public void receiveMsg(OrderReturnReasonEntity entity, Channel channel,
                           Message message) {
        /**伪代码如下*/
        /**表示在通道内的消息的一个标签，是一个在通道内自增的数字*/
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        /**其中两个参数，第一个是消息的标签，第二个表示是否是批量处理*/
        try {
            /**执行之后，表示确认消息收到*/
            channel.basicAck(deliveryTag, false);
        } catch (IOException e) {
            /**网络中断*/
            e.printStackTrace();
        }
        System.out.println("接收到订单退回原因实体类.." + entity);
    }

    /**
     * @param entity
     */
    @RabbitHandler
    public void receiveMsg(OrderEntity entity) {
        System.out.println("接收到订单实体类..." + entity);
    }


}
